//
//  TestDragRectangle.cpp
//  NanoOSX
//
//  Created by Jeppe Nielsen on 12/24/13.
//  Copyright (c) 2013 Jeppe Nielsen. All rights reserved.
//

#include "GameState.hpp"
#include "Engine.hpp"
#include "GameWorld.hpp"
#include "DragSelector.hpp"
#include "RenderSystem.hpp"
#include "TouchSystem.hpp"
#include "DraggableSystem.hpp"
#include "SelectableDragSystem.hpp"
#include "SelectionVisualizer.hpp"

#include <algorithm>

using namespace Nano;

class TestDragRectangle : public GameState {
    
    
    class RotatorSystem : public GameSystem {
    public:
        void Initialize() {
            AddComponent<Transform>();
            AddComponent<Selectable>();
            rot =0;
        }
        
        void Update(float dt) {
            for (ObjectCollection::const_iterator it = Objects().begin(); it!=Objects().end(); ++it) {
                GameObject* go = (*it);
                if (go->GetComponent<Selectable>()->Selected) {
                    go->GetComponent<Transform>()->Rotation = rot;
                }
                
            }
            rot += dt;
        }
        
        float rot;
    };
    
    
    
    void Initialized() {
        
        dragSelector = world.CreateSystem<DragSelector>();
        dragSelector->Setup(Viewport(), Input);
        
        renderer = world.CreateSystem<RenderSystem>();
        world.CreateSystem<TouchSystem>()->Input = &Input;
        world.CreateSystem<DraggableSystem>();
        world.CreateSystem<SelectableDragSystem>();
        
        //world.CreateSystem<RotatorSystem>();
        world.CreateSystem<SelectionVisualizer>();
        
        
        GameObject* cameraObject = world.CreateObject();
        cameraObject->AddComponent<Transform>()->Position = {0,0,50};
        cameraObject->AddComponent<Camera>()->Viewport = Viewport();
        
        
        for (int y =0; y<10; y++) {
        
        for (int x = 0; x<10; x++) {
        
            cube = world.CreateObject();
            cube->AddComponent<Transform>()->Position = { x * 4, y * 4,0 };
            cube->AddComponent<Mesh>()->AddCube(0, 1);
            cube->AddComponent<Material>();
            cube->AddComponent<Selectable>();
            cube->AddComponent<Touchable>();
            cube->AddComponent<Draggable>()->Movement = Draggable::MovementMode::XYPlane;
            
        }
        }
        
        
    }
    
    void Update(float dt) {
        
        
        world.Update(dt);
    }
    
    void Render() {
        glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
        //glDisable(GL_CULL_FACE);
        
        renderer->Render();
        dragSelector->Render();
    }
    
    GameWorld world;
    DragSelector* dragSelector;
    GameObject* camera;
    RenderSystem* renderer;
    GameObject* cube;
    
    
};

/*
int main() {
    Engine e;
    e.Start<TestDragRectangle>();
    return 0;
}
*/